package _05_二叉树;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class _590_N叉树的后序遍历 {

    // 递归
    public List<Integer> postorder2(Node root) {
        List<Integer> list = new ArrayList<>();
        if (root == null) return list;

        postorder(root, list);
        return list;
    }

    public void postorder(Node root, List<Integer> list) {
        if (root == null) return;
        List<Node> nodes = root.children;
        if (nodes != null && !nodes.isEmpty()) {
            for (Node node : nodes) {
                postorder(node, list);
            }
        }
        list.add(root.val);
    }

    // 迭代
    public List<Integer> postorder(Node root) {
        List<Integer> list = new ArrayList<>();
        if (root == null) return list;
        Stack<Node> stack = new Stack<>();
        stack.push(root);
        Node prev = null;
        while (!stack.isEmpty()) {
            root = stack.peek();
            if (root.children == null || root.children.isEmpty() || root.children.contains(prev)) {
                // 直接遍历根节点
                list.add(root.val);
                root = stack.pop();
                prev = root;
            } else {
                for (int i = root.children.size() - 1; i >= 0 ; i--) {
                    stack.push(root.children.get(i));
                }
            }
        }
        return list;
    }

}
